package com.kly.chatter.api.application.task;


import cn.hutool.core.net.NetUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.common.api.Response;
import com.fqgj.common.utils.CollectionUtils;
import com.kly.chatter.db.dao.ChatterImRewardDao;
import com.kly.chatter.db.dao.ChatterRewardInfoDao;
import com.kly.chatter.db.dao.PrivateUnlockRewardDao;
import com.kly.chatter.db.entity.ChatterImRewardDBO;
import com.kly.chatter.db.entity.ChatterRewardInfoEntity;
import com.kly.chatter.db.entity.PrivateUnlockRewardDBO;
import com.kly.user.chatterService.ChatterUserService;
import com.kly.user.dto.chatter.response.UserChatterDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * 私密照片、私密视频解锁奖励
 */
@Slf4j
@Component
public class ChatterRewardInfoTask {

    @Resource
    ChatterRewardInfoDao chatterRewardInfoDao;
    @Resource
    PrivateUnlockRewardDao privateUnlockRewardDao;
    @Resource
    ChatterImRewardDao chatterImRewardDao;
    @Resource
    ChatterUserService chatterUserService;
    @NacosValue(value = "${task.job.executor.ip}", autoRefreshed = true)
    private String taskJobExecutor;

    private String localIP = NetUtil.getLocalhostStr();

    private static final Integer privatePhoto = 1;

    private static final Integer privateVideo = 2;

    @Scheduled(fixedDelay = 60000 * 5)
    public void executePrivateUnlockRewards() {

        if (!taskJobExecutor.contains(localIP)) {
            log.info("=============ChatterRewardInfoTask, currentLocalAddress:{}, onlyExecuteTaskIn:{}", localIP, taskJobExecutor);
            return;
        }

        final Response<List<UserChatterDto>> allChattersResponse = chatterUserService.getAllChatters();
        if (allChattersResponse == null || !allChattersResponse.isSuccess() || CollectionUtils.isEmpty(allChattersResponse.getData())) {
            return;
        }

        log.info("==== PrivatePhoto 数据统计");
        executePPVTaskByType(privatePhoto, allChattersResponse.getData());

        log.info("==== PrivateVideo 数据统计");
        executePPVTaskByType(privateVideo, allChattersResponse.getData());

        log.info("==== ChatSessionNum 数据统计");
        executeChatTaskByType(allChattersResponse.getData());

    }

    private void executePPVTaskByType(Integer ppvType, List<UserChatterDto> allChatters) {
        // 当日奖励统计
        final List<PrivateUnlockRewardDBO> privateUnlockRewards = privateUnlockRewardDao.listPrivateUnlockReward(ppvType);
        if (CollectionUtils.isEmpty(privateUnlockRewards)) {
            return;
        }

        // 获取当日统计情况数据
        final List<ChatterRewardInfoEntity> chatterRewardInfoEntities = chatterRewardInfoDao.listChatterRewardInfoToday();
        for (PrivateUnlockRewardDBO record : privateUnlockRewards) {
            ChatterRewardInfoEntity chatterRewardInfo = getChatterRewardInfoEntity(chatterRewardInfoEntities, record);
            final UserChatterDto chatter = allChatters.parallelStream().filter(o -> record.getChatterCode().equals(o.getChatterUserCode())).findAny().orElse(null);
            storeChatterInfoData(record, chatterRewardInfo, ppvType, chatter);
        }
    }


    private void executeChatTaskByType(List<UserChatterDto> allChatters) {
        // chat数据
        final List<ChatterImRewardDBO> chatterImRewards = chatterImRewardDao.listChatterImRewardToday();
        if (CollectionUtils.isEmpty(chatterImRewards)) {
            return;
        }

        // 获取当日统计情况数据
        final List<ChatterRewardInfoEntity> chatterRewardInfoEntities = chatterRewardInfoDao.listChatterRewardInfoToday();
        for (ChatterImRewardDBO record : chatterImRewards) {
            ChatterRewardInfoEntity chatterRewardInfo = getChatterImRewardInfoEntity(chatterRewardInfoEntities, record);
            final UserChatterDto chatter = allChatters.parallelStream().filter(o -> record.getChatterCode().equals(o.getChatterUserCode())).findAny().orElse(null);
            storeChatInfo(record, chatterRewardInfo, chatter);
        }
    }

    private void storeChatInfo(ChatterImRewardDBO record, ChatterRewardInfoEntity chatterRewardInfo, UserChatterDto chatter) {
        if (chatterRewardInfo == null) {
            chatterRewardInfo = new ChatterRewardInfoEntity();
        }
        chatterRewardInfo.setChatterUserCode(record.getChatterCode());
        if (chatter != null) {
            chatterRewardInfo.setChatterAccount(chatter.getChatterAccount());
            chatterRewardInfo.setChatterNickName(chatter.getChatterNickName());
        }
        chatterRewardInfo.setCurrentDt(record.getRewardDate());
        chatterRewardInfo.setNoneVipChatUnit(record.getNoneVipChatNum());
        chatterRewardInfo.setVipChatUnit(record.getVipChatNum());
        chatterRewardInfo.setChatRewardAmount(record.getReward());
        chatterRewardInfo.setChatterRewardTotalAmount(chatterRewardInfo.getPpRewardAmount().add(chatterRewardInfo.getPvRewardAmount()).add(chatterRewardInfo.getChatRewardAmount()));
        if (chatterRewardInfo.getId() == null) {
            chatterRewardInfoDao.insert(chatterRewardInfo);
        } else {
            chatterRewardInfoDao.updateByPrimaryKey(chatterRewardInfo);
        }
    }

    private void storeChatterInfoData(PrivateUnlockRewardDBO record, ChatterRewardInfoEntity chatterRewardInfo, Integer ppvType, UserChatterDto chatter) {
        if (chatterRewardInfo == null) {
            chatterRewardInfo = new ChatterRewardInfoEntity();
        }
        chatterRewardInfo.setChatterUserCode(record.getChatterCode());
        if (chatter != null) {
            chatterRewardInfo.setChatterAccount(chatter.getChatterAccount());
            chatterRewardInfo.setChatterNickName(chatter.getChatterNickName());
        }
        chatterRewardInfo.setCurrentDt(record.getRewardDate());
        if(ppvType.equals(privatePhoto)) {
            chatterRewardInfo.setPpTotalTime1(record.getPpvUnitsInTime1());
            chatterRewardInfo.setPpTotalTime2(record.getPpvUnitsInTime2());
            chatterRewardInfo.setPpRewardAmount(record.getReward());

        }
        if (ppvType.equals(privateVideo)) {
            chatterRewardInfo.setPvTotalTime1(record.getPpvUnitsInTime1());
            chatterRewardInfo.setPvTotalTime2(record.getPpvUnitsInTime2());
            chatterRewardInfo.setPvRewardAmount(record.getReward());

        }
        chatterRewardInfo.setChatterRewardTotalAmount(chatterRewardInfo.getPpRewardAmount().add(chatterRewardInfo.getPvRewardAmount()).add(chatterRewardInfo.getChatRewardAmount()));
        log.info("chatterRewardInfo:{}", JSONObject.toJSONString(chatterRewardInfo));
        if (chatterRewardInfo.getId() == null) {
            chatterRewardInfoDao.insert(chatterRewardInfo);
        } else {
            chatterRewardInfoDao.updateByPrimaryKey(chatterRewardInfo);
        }
    }

    private ChatterRewardInfoEntity getChatterRewardInfoEntity(List<ChatterRewardInfoEntity> chatterRewardInfoEntities, PrivateUnlockRewardDBO record) {
        return chatterRewardInfoEntities.parallelStream().filter(o -> o.getChatterUserCode().equals(record.getChatterCode()) && o.getCurrentDt().equals(record.getRewardDate())).findAny().orElse(null);
    }

    private ChatterRewardInfoEntity getChatterImRewardInfoEntity(List<ChatterRewardInfoEntity> chatterRewardInfoEntities, ChatterImRewardDBO record) {
        return chatterRewardInfoEntities.parallelStream().filter(o -> o.getChatterUserCode().equals(record.getChatterCode()) && o.getCurrentDt().equals(record.getRewardDate())).findAny().orElse(null);
    }
}
